package com.markuppages.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;

import com.markuppages.client.GreetingService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
GreetingService {

	public String greetServer(String input) {
		StringWriter writer = new StringWriter();
		try {
			URL url = new URL(input);
			String contentEncoding = url.openConnection().getContentEncoding() == null ? "Windows-1251" : url.openConnection().getContentEncoding();
			BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), contentEncoding));
			writer.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=" + contentEncoding + "\">");
			writer.append("<base href=\"" + input + "\"/>");
			String line;
			while ((line = reader.readLine()) != null) {
				writer.append(line);
			}

			reader.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}  catch (IOException e) {
			e.printStackTrace();
		}

		return writer.toString();
	}
}
